package utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBHelper {
    private static String driver = null;
    private static String url = null;
    private static String user = null;
    private static String password = null;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        try {
            System.out.println(Thread.currentThread().getContextClassLoader().getResource("/").getPath());
            String filename = Thread.currentThread().getContextClassLoader().getResource("/").getPath()+"\\JDBC.properties";
            Properties properties = new Properties();
            InputStream inputStream = new BufferedInputStream(new FileInputStream(filename));
            properties.load(inputStream);
            driver = properties.getProperty("db.driver").trim();
            url = properties.getProperty("db.url").trim();
            user = properties.getProperty("db.user").trim();
            password = properties.getProperty("db.password").trim();
            inputStream.close();

            Class.forName(driver);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 连接数据库的方法，将conn进行返回
    public static Connection getConnection()  {
        Connection conn = null;
        try {
            conn = threadLocal.get();
            if (conn == null) {
                conn = DriverManager.getConnection(url, user, password);
                System.out.println("数据库连接上了");
                threadLocal.set(conn);
            }
        } catch (Exception e){
            // 输出异常
            e.printStackTrace();
        }
        return  conn;
    }

    // 关闭数据库的方法
    public static void close(){
        Connection conn = threadLocal.get();
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        threadLocal.set(null);
    }

    public static void main(String[] args) {
        // 调用连接数据的方法
        DBHelper.getConnection();
//        String filename = "E:\\Code\\campus-lost-and-found-system\\src\\main\\resources\\JDBC.properties";
//        System.out.println(DBHelper.class.getClassLoader().getResource("JDBC.properties").getPath());

    }
}